<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Listener;

use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Config\Annotation\Mapping\Config;
use Swoft\Consul\Agent;
use Swoft\Consul\KV;
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Http\Server\HttpServer;
use Swoft\Log\Helper\CLog;
use Swoft\Server\SwooleEvent;

/**
 * Class RegisterServiceListener
 *
 * @since 2.0
 *
 * @Listener(event=SwooleEvent::START)
 */
class RegisterServiceListener implements EventHandlerInterface
{
    /**
     * @Inject()
     *
     * @var Agent
     */
    private $agent;

    /**
     * @Inject()
     * @var KV
     */
    private $kv;

    /**
     * @Config("consul.consul_server_name")
     * @var
     */
    private $serverName;

    /**
     * @param EventInterface $event
     */
    public function handle(EventInterface $event): void
    {
        /** @var HttpServer $httpServer */
        $httpServer = $event->getTarget();
        $ip         = env('HOST');
        $port       = 18306;
        print_r([
            'a' => env('CONSUL_CHECK_TYPE', 'Acp'),
            'b' => env('CONSUL_CHECK_IP', '192.168.150.133'),
            'c' => env('CONSUL_CHECK_PORT', '18357'),
        ]);
        $prefix    = $this->serverName;
        $checkType = env('CONSUL_CHECK_TYPE', 'tcp');
        $service   = [
            'ID'                => getConsulServerId($prefix),
            'Name'              => $this->serverName,
            'Tags'              => [
                'rpc'
            ],
            'Address'           => $ip,
            'Port'              => $httpServer->getPort(),
            'Meta'              => [
                'version' => '1.0'
            ],
            'EnableTagOverride' => false,
            'Weights'           => [
                'Passing' => 10,
                'Warning' => 1
            ],
            //consul 健康检测
            'Check'             => [
                'id'         => getConsulServerId($prefix),
                'name'       => 'swoft.goods.server',
                "$checkType" => env('CONSUL_CHECK_IP') . ':' . env('CONSUL_CHECK_PORT'),
                'interval'   => '10s',
                'timeout'    => '1s',
            ],
        ];


        // Register
        $this->agent->registerService($service);
        // 注册当前服务KV用于nginx的动态负载均衡
        $this->kv->put('/upstream/swoft_server/' . env('CONSUL_CHECK_IP') . ':' . env('CONSUL_CHECK_PORT'), '{"max_fails":2,"fail_timeout":10}');
        CLog::info('Swoft rpc register service success by consul!');
    }
}
